package com.yanqu.road.server.cmd.activity.seacraftsouthsea;

import com.yanqu.road.entity.activity.seacraft.config.SeacraftSouthSeaActivityConfig;
import com.yanqu.road.entity.player.UserBaseInfo;
import com.yanqu.road.entity.player.UserInfo;
import com.yanqu.road.entity.player.UserPatrons;
import com.yanqu.road.entity.union.UnionBaseInfo;
import com.yanqu.road.entity.union.cross.CrossUnionInfo;
import com.yanqu.road.entity.union.cross.CrossUnionMember;
import com.yanqu.road.logic.pb.PlayerBasePb;
import com.yanqu.road.logic.pb.UnionBasePb;
import com.yanqu.road.pb.activity.SeacraftSouthSeaProto;
import com.yanqu.road.pb.union.UnionProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.command.Command;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.seacraft.SeacraftSouthSeaModule;
import com.yanqu.road.server.manger.activity.seacraft.SeacraftSouthSeaMgr;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.manger.union.CrossUnionMgr;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.CrossProtocol;
import com.yanqu.road.server.protocol.GameProtocol;
import com.yanqu.road.utils.string.StringUtils;
import io.netty.channel.ChannelHandlerContext;

import java.util.*;

/**
 * @Description
 * @Author cwq
 * @Data 2022/1/20 15:28
 */
@Cmd(code = GameProtocol.S_SEACRAFT_SOUTH_SEA_LOCK_JOIN_UNION_FROM_CROSS, desc = "海上争霸 南海丝路 锁定晋级名单 跨服返回区服 协议")
public class SeacraftSouthSeaLockJoinUnionFromCrossCmd implements Command {

    @Override
    public void execute(ChannelHandlerContext ctx, YanQuMessage packet) throws Exception {
        SeacraftSouthSeaProto.SeacraftSouthSeaSynPromotionUnionCrossToGameMsg builder = SeacraftSouthSeaProto.SeacraftSouthSeaSynPromotionUnionCrossToGameMsg.parseFrom(packet.getBytes());
        synchronized (SeacraftSouthSeaLockJoinUnionFromCrossCmd.class){
            if(!CrossUnionMgr.isAllSync()){
                return;
            }
            int activityId = builder.getActivityId();
            SeacraftSouthSeaMgr.getLogger().info("收到锁定晋级 南海丝路 的联盟名额 activityId：{},需要同步的联盟returnUnionInfoListList:{},userTeamInfoList：{}", activityId, StringUtils.listToString(builder.getReturnUnionInfoListList(),","),StringUtils.listToString(builder.getReturnUserTeamListList(),","));
            // 过滤不属于当前区服的活动
            if(SeacraftSouthSeaMgr.getActivityInfo().getActivityId() != activityId){
                SeacraftSouthSeaMgr.getLogger().info("过滤不属于当前区服的活动 curActivityId : {}",SeacraftSouthSeaMgr.getActivityInfo().getActivityId());
                return;
            }
            List<SeacraftSouthSeaProto.SeacraftSouthSeaPromotionUnionMsg> roundPromotionList = builder.getPromotionListList();
            roundPromotionList.forEach(e -> {
                SeacraftSouthSeaMgr.getLogger().info("收到锁定晋级 南海丝路 的联盟名额 activityId：{},round:{},晋级联盟unionList:{}", activityId, e.getRound(), StringUtils.listToString(e.getUnionIdList(), ","));
                if (!SeacraftSouthSeaMgr.getRoundJoinUnionMap(builder.getGroupId()).containsKey(e.getRound())) {
                    // 同步玩家数据
                    for (String unionId : e.getUnionIdList()) {
                        CrossUnionInfo unionInfo = CrossUnionMgr.getUnionInfoMap().get(unionId);
                        Map<Long, CrossUnionMember> memberMap = CrossUnionMgr.getUnionMemberMap(unionId);
                        if (unionInfo != null && memberMap != null) {
                            for (CrossUnionMember item : memberMap.values()) {
                                GamePlayer member = GamePlayerMgr.getOnlinePlayer(item.getUserId());
                                if (member != null) {
                                    member.getModule(SeacraftSouthSeaModule.class).synUserData();
                                }
                            }
                        }
                    }
                }
                SeacraftSouthSeaMgr.getRoundJoinUnionMap(builder.getGroupId()).put(e.getRound(), e.getUnionIdList());
            });
            SeacraftSouthSeaProto.SeacraftSouthSeaSynPromotionUnionGameToCrossMsg.Builder toCrossMsg = SeacraftSouthSeaProto.SeacraftSouthSeaSynPromotionUnionGameToCrossMsg.newBuilder();
            toCrossMsg.setActivityId(activityId);
            if (builder.getReturnUnionInfoListList().size() > 0) {
                // 返回需要同步的联盟数据 以及玩家数据
                for (String unionId : builder.getReturnUnionInfoListList()) {
                    CrossUnionInfo unionInfo = CrossUnionMgr.getUnionInfoMap().get(unionId);
                    if (unionInfo != null) {
                        UserInfo masterUser = UserMgr.getUserInfo(unionInfo.getMasterUserId());
                        if(masterUser == null){
                            continue;
                        }
                        SeacraftSouthSeaProto.SeacraftSouthSeaUnionInfo.Builder seacraftSouthSeaUnionInfo = SeacraftSouthSeaProto.SeacraftSouthSeaUnionInfo.newBuilder();
                        seacraftSouthSeaUnionInfo.setUnionId(unionId);
                        UnionBaseInfo unionBaseInfo = CrossUnionMgr.parseUnionBaseInfo(unionInfo);
                        UnionProto.UnionBaseTempMsg.Builder unionMsg = UnionBasePb.parseUnionBaseTempMsg(unionBaseInfo);
                        seacraftSouthSeaUnionInfo.setUnionBaseInfo(unionMsg);
                        // 联盟信息
                        Map<Long, CrossUnionMember> memberMap = CrossUnionMgr.getUnionMemberMap(unionId);
                        if (memberMap != null) {
                            for (CrossUnionMember member : memberMap.values()) {
                                SeacraftSouthSeaProto.SeacraftSouthSeaUnionMemberInfo.Builder memberInfo = SeacraftSouthSeaProto.SeacraftSouthSeaUnionMemberInfo.newBuilder();
                                memberInfo.setServerId(member.getServerId());
                                memberInfo.setUserId(member.getUserId());
                                seacraftSouthSeaUnionInfo.addMemberInfoList(memberInfo);
                            }
                        }
                        toCrossMsg.addUnionList(seacraftSouthSeaUnionInfo);
                    }
                }
            }
            // 返回门客数据
            if(builder.getReturnUserTeamListList().size() > 0){
                for (long userId : builder.getReturnUserTeamListList()) {
                    // 同步锁定联盟的联盟成员给跨服
                    UserBaseInfo userBaseInfo = UserMgr.getUserBaseInfo(userId, GameServer.getInstance().getServerId());
                    if(userBaseInfo == null) {
                        continue;
                    }
                    SeacraftSouthSeaProto.SeacraftSouthSeaLockUserInfo.Builder memberInfo = SeacraftSouthSeaProto.SeacraftSouthSeaLockUserInfo.newBuilder();
                    memberInfo.setUserId(userId);
                    memberInfo.setPlayerInfo(PlayerBasePb.parsePlayerBaseTempMsg(userBaseInfo));
                    // 锁定 队伍
                    Map<Integer, List<UserPatrons>> patronMap = SeacraftSouthSeaMgr.getPatronsMap(userId);
                    for (Map.Entry<Integer, List<UserPatrons>> entry : patronMap.entrySet()) {
                        SeacraftSouthSeaProto.SeacraftSouthSeaLockTeamInfo.Builder teamInfo = SeacraftSouthSeaProto.SeacraftSouthSeaLockTeamInfo.newBuilder();
                        teamInfo.setType(entry.getKey());
                        entry.getValue().forEach(e -> {
                            if (teamInfo.getPatronsBuilderList().size() >= SeacraftSouthSeaActivityConfig.getTeamNum()) {
                                // 只取前六名
                                return;
                            }
                            teamInfo.addPatrons(SeacraftSouthSeaMgr.builderSeacraftSouthSeaPatronsEntity(e));
                        });
                        memberInfo.addTeamInfo(teamInfo);
                    }
                    toCrossMsg.addUserTeamInfoList(memberInfo);
                }
            }
            if(toCrossMsg.getUnionListList().size() > 0 || toCrossMsg.getUserTeamInfoListList().size() > 0){
                GamePlayerMgr.sendUnionActivityGroupPacket(CrossProtocol.C2_SEACRAFT_SOUTH_SEA_SYN_PROMOTION_UNION, toCrossMsg, 0, activityId, builder.getGroupId());
            }
        }
    }
}
